<template>
  <el-container class="data-content">
    <el-aside width="300px" v-loading="showDicloading">
      <el-container>
        <el-header>
          <el-input placeholder="输入关键字进行过滤" v-model="dicFilterText" clearable></el-input>
        </el-header>
        <el-main class="nopadding">
          <el-tree ref="dic" class="menu" node-key="id" :data="dicList" :props="dicProps" :highlight-current="true"
                   :expand-on-click-node="false" :filter-node-method="dicFilterNode" @node-click="dicClick">
            <template #default="{node, data}">
							<span class="custom-tree-node">
								<span class="label">{{ data.title }}</span>
								<span class="code">{{ data.dataKey }}</span>
								<span class="do">
									<el-button-group>
										<el-button :icon="Edit" size="small" @click.stop="dicEdit(data)"></el-button>
										<el-button :icon="Delete" size="small" @click.stop="dicDel(node, data)"></el-button>
									</el-button-group>
								</span>
							</span>
            </template>
          </el-tree>
        </el-main>
        <el-footer style="height:51px;">
          <el-button type="primary" size="small" icon="el-icon-plus" style="width: 100%;" @click="addDic">字典分类
          </el-button>
        </el-footer>
      </el-container>
    </el-aside>
    <el-container class="is-vertical">
      <el-header>
        <div class="left-panel">
          <el-button type="primary" :icon="Plus" @click="addInfo" :disabled="selectData.id ===undefined"></el-button>
          <el-button type="danger" plain :icon="Delete" :disabled="selection.length==0"
                     @click="batch_del"></el-button>
        </div>
      </el-header>
      <el-main class="nopadding">
        <el-table ref="table" row-key="id" :data="tableData.data" @selection-change="selectionChange"
                  stripe :paginationLayout="'prev, pager, next'">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column label="排序号" prop="sortNum" width="150" sortable></el-table-column>
          <el-table-column label="名称" prop="dataCode" width="150"></el-table-column>
          <el-table-column label="键值" prop="dataValue"  ></el-table-column>
          <el-table-column label="操作" fixed="right" align="right" width="120">
            <template #default="scope">
              <el-button-group>
                <el-button text type="primary" size="small" @click="table_edit(scope.row, scope.$index)">编辑
                </el-button>
                <el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row, scope.$index)">
                  <template #reference>
                    <el-button text type="danger" size="small">删除</el-button>
                  </template>
                </el-popconfirm>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
  </el-container>

  <dic-dialog v-if="dialog.dic" ref="dicDialog" @success="handleDicSuccess" @closed="dialog.dic=false"></dic-dialog>

  <list-dialog v-if="dialog.list" ref="listDialog" @success="handleListSuccess"
               @closed="dialog.list=false"></list-dialog>

</template>

<script>
import dicDialog from './dic.vue'
import listDialog from './list.vue'
import Sortable from 'sortablejs'
import {Delete, Plus, Edit, Search} from '@element-plus/icons-vue'

export default {
  name: 'dic',
  components: {
    dicDialog,
    listDialog
  },
  data() {
    return {
      Delete: Delete,
      Plus: Plus,
      Search: Search,
      Edit: Edit,
      dialog: {
        dic: false,
        info: false
      },
      showDicloading: true,
      dicList: [],
      dicFilterText: '',
      dicProps: {
        label: 'name'
      },
      listApi: null,
      listApiParams: {},
      selection: [],
      selectData: {},
      tableData: {}
    }
  },
  watch: {
    dicFilterText(val) {
      this.$refs.dic.filter(val);
    }
  },
  mounted() {
    this.getDic()
    //this.rowDrop()
  },
  methods: {
    //加载树数据
    async getDic() {
      let res = await this.$http.form("/dict/list", {});
      this.showDicloading = false;
      this.dicList = res.data;
    },
    //树过滤
    dicFilterNode(value, data) {
      if (!value) return true;
      const targetText = data.title + data.dictKey;
      return targetText.indexOf(value) !== -1;
    },
    //树增加
    addDic() {
      this.dialog.dic = true
      this.$nextTick(() => {
        this.$refs.dicDialog.open()
      })
    },
    //编辑树
    dicEdit(data) {
      this.dialog.dic = true
      this.$nextTick(() => {
        this.$refs.dicDialog.open('update').setData(data)
      })
    },
    //树点击事件
    async dicClick(data) {
      this.selectData = data;
      let res = await this.$http.form(`/dictItem/list`, {dict: data.id});
      if (res.code === 200) {
        this.tableData = res;
      }
    },
    //删除树
    dicDel(node, data) {
      this.$confirm(`确定删除 ${data.title} 项吗？`, '提示', {
        type: 'warning'
      }).then(async () => {
        this.showDicloading = true;

        let res = await this.$http.form(`/dict/delete`, data);
        if (res.code !== 200) {
          this.$message.error(res.msg)
          return;
        }

        //删除节点是否为高亮当前 是的话 设置第一个节点高亮
        var dicCurrentKey = this.$refs.dic.getCurrentKey();
        this.$refs.dic.remove(data.id)
        if (dicCurrentKey === data.id) {
          var firstNode = this.dicList[0];
          if (firstNode) {
            this.$refs.dic.setCurrentKey(firstNode.id);
            this.$refs.table.upData({
              code: firstNode.code
            })
          } else {
            this.listApi = null;
            this.$refs.table.tableData = []
          }
        }

        this.showDicloading = false;
        this.$message.success("操作成功")
      }).catch(() => {

      })
    },
    //行拖拽
    rowDrop() {
      const _this = this
      const tbody = this.$refs.table.$el.querySelector('.el-table__body-wrapper tbody')
      Sortable.create(tbody, {
        handle: ".move",
        animation: 300,
        ghostClass: "ghost",
        onEnd({newIndex, oldIndex}) {
          const tableData = _this.$refs.table.tableData
          const currRow = tableData.splice(oldIndex, 1)[0]
          tableData.splice(newIndex, 0, currRow)
          _this.$message.success("排序成功")
        }
      })
    },
    //添加明细
    addInfo() {
      let self=this;
      this.dialog.list = true

      this.$nextTick(() => {
        this.$refs.listDialog.open(self.selectData.id)
      })
    },
    //编辑明细
    table_edit(row) {
      this.dialog.list = true
      this.$nextTick(() => {
        this.$refs.listDialog.open(row.dict).setData(row)
      })
    },
    //删除明细
    async table_del(row, index) {
      const reqData = {id: row.id};
      let res = await this.$http.form(`/dictItem/delete`, reqData);
      if (res.code === 200) {
        //this.$refs.table.tableData.splice(index, 1);
        this.loadItems();
        this.$message.success("删除成功")
      } else {
        this.$alert(res.msg, "提示", {type: 'error'})
      }
    },
    async  loadItems(){
      let res = await this.$http.form(`/dictItem/list`, {dict: this.selectData.id});
      this.tableData=res;
    },
    //批量删除
    async batch_del() {
      this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, '提示', {
        type: 'warning'
      }).then(async () => {
        const loading = this.$loading();
        for (const item of this.selection) {
          const reqData = {id: item.id};
            await this.$http.form(`/dictItem/delete`, reqData);
        }
        await this.loadItems();
        loading.close();
        this.$message.success("操作成功")
      }).catch(() => {

      })
    },
    //提交明细
    saveList() {
      this.$refs.listDialog.submit(async (formData) => {
        this.isListSaveing = true;
        var res = await this.$API.demo.post.post(formData);
        this.isListSaveing = false;
        if (res.code == 200) {
          //这里选择刷新整个表格 OR 插入/编辑现有表格数据
          this.listDialogVisible = false;
          this.$message.success("操作成功")
        } else {
          this.$alert(res.message, "提示", {type: 'error'})
        }
      })
    },
    //表格选择后回调事件
    selectionChange(selection) {
      this.selection = selection;
    },
    //表格内开关事件
    changeSwitch(val, row) {
      //1.还原数据
      row.yx = row.yx == '1' ? '0' : '1'
      //2.执行加载
      row.$switch_yx = true;
      //3.等待接口返回后改变值
      setTimeout(() => {
        delete row.$switch_yx;
        row.yx = val;
        this.$message.success(`操作成功id:${row.id} val:${val}`)
      }, 500)
    },
    //本地更新数据
    handleDicSuccess(data, mode) {
     this.getDic();
    },
    //本地更新数据
    handleListSuccess(data, mode) {
       this.loadItems();
    }
  }
}
</script>

<style scoped>
.menu:deep(.el-tree-node__label) {
  display: flex;
  flex: 1;
  height: 100%;
}

.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 24px;
  height: 100%;
}

.custom-tree-node .code {
  font-size: 12px;
  color: #999;
}

.custom-tree-node .do {
  display: none;
}

.custom-tree-node:hover .code {
  display: none;
}

.custom-tree-node:hover .do {
  display: inline-block;
}
</style>
